import os, re


def transform(code):
    code_list, semi_list, indent_stack = [], [], []
    for line in code.split("\n"):  # 分号处理
        if "//" in line:
            line = line.split("//")[0][:-2]
        if re.search("\S", line):
            if not re.search("@\S+\(", line) and line[-1] != ":": line += ";"
            semi_list.append(line)

    for line in semi_list:  # 基于缩进的冒号处理
        retrive = ""
        while indent_stack and indent_stack[-1] >= len(re.findall("^(\s*)\S", line)[0]):
            retrive += " " * indent_stack[-1] + "}\n"
            indent_stack.pop()

        if line[-1] == ":":
            line = line.replace(":", " {")
            indent_stack.append(len(re.findall("^(\s*)\S", line)[0]))
        elif ":" in line:
            line = line.replace(":", " {") + " }"

        line = retrive + line
        code_list.append(line)
    indent_stack.reverse()  # 回收未闭环的大括号
    for i in indent_stack:
        code_list.append(" " * i + "}")
    return "\n".join(code_list)


# os.system('chcp 65001')  # 原编码936仅能显示GBK编码的中文
# 默认r，r+:头指针读写(覆写)，w+:全清头指针读写，a:尾指针写，a+:尾指针读写
with open("test.java", encoding="utf-8") as code:
    new_code = transform(code.read())

name = "main"
if re.search("public.*class (\S+)", new_code):
    name = re.findall("public.*class (\S+)", new_code)[0]

with open(f"{name}.java", mode="w", encoding="utf-8") as code:
    code.write(new_code)

os.environ['JAVA_TOOL_OPTIONS'] = '-Dfile.encoding=UTF-8'  # JVM环境变量设置
os.system(f"javac {name}.java")
os.system("java Test")